package com.ajview.common.utils;

import com.ajview.common.core.domain.bo.LoginUser;
import com.ajview.common.core.exception.ServiceGlobalException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @author ZhangJunJie
 * @Date 2022-04-29
 * <p>
 * 概要：Security的工具类
 */
public class SecurityUtils {

    public static String AUTHENTICATION_NAME = "anonymousUser";

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 设置Authentication
     */
    public static void setAuthentication(Authentication authentication) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    /**
     * 获取已认证用户的model对象
     *
     * @return
     */
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new ServiceGlobalException("user-security", "system.init.param.exception", new Object[]{"用户信息"}, "获取用户信息错误", e);
        }
    }

    /**
     * 获取已认证用户的用户id
     *
     * @return
     */
    public static Long getLoginUserId() {
        try {
            return getLoginUser().getUserId();
        } catch (Exception e) {
            throw new ServiceGlobalException("user-security", "system.init.param.exception", new Object[]{"用户编号"}, "获取用户userName错误", e);
        }
    }


    /**
     * 获取已认证用户的用户姓名
     *
     * @return
     */
    public static String getLoginUserName() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new ServiceGlobalException("user-security", "system.init.param.exception", new Object[]{"用户userName"}, "获取用户userName错误", e);
        }
    }

    /**
     * 获取已认证用户的部门id
     *
     * @return
     */
    public static Long getLoginUserDeptId() {
        try {
            return getLoginUser().getDeptId();
        } catch (Exception e) {
            throw new ServiceGlobalException("user-security", "system.init.param.exception", new Object[]{"用户userName"}, "获取用户userName错误", e);
        }
    }

}
